package io.github.annyylxyms.gynregistry.health;

import io.github.annyylxyms.gynregistry.model.InstanceMeta;
import io.github.annyylxyms.gynregistry.service.GynRegistryService;
import io.github.annyylxyms.gynregistry.service.RegistryService;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 探活定时任务
 */
@Slf4j
public class GynHealthChecker implements HealthChecker {
    RegistryService registryService;

    public GynHealthChecker(RegistryService registryService) {
        this.registryService = registryService;
    }

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    long timeout = 20 * 1000;


    @Override
    public void start() {
        executor.scheduleWithFixedDelay(
                () -> {
                    log.info(" ===> health checker running...");
                    //找出map里时间戳超过X秒的实例
                    long now = System.currentTimeMillis();
                    GynRegistryService.TIMESTAMPS.keySet().stream().forEach(serviceAndInst -> {
                        long timestamp = GynRegistryService.TIMESTAMPS.get(serviceAndInst);
                        //timeout秒内没有请求renew刷新时间戳，就自动下线这个服务
                        if (now - timestamp > timeout) {
                            log.info(" ===> health checker: {} is down ", serviceAndInst);
                            int index = serviceAndInst.indexOf("@");
                            String service = serviceAndInst.substring(0, index);
                            String url = serviceAndInst.substring(index + 1);
                            InstanceMeta instance = InstanceMeta.from(url);
                            registryService.unregister(service, instance);
                            GynRegistryService.TIMESTAMPS.remove(serviceAndInst);
                        }
                    });

                }, 10, 10, TimeUnit.SECONDS);
    }

    @Override
    public void stop() {
        executor.shutdown();
    }
}
